package com.only.common.enums;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;

import com.only.common.exception.BizExceptionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.convert.converter.Converter;

import java.util.Arrays;
import java.util.Map;

/**
 * @author only
 * @date 2023/6/14
 * @description
 */
public class GeneralCodeEnumConverter<T extends GeneralCodeEnum> implements Converter<String, T> {
    private static final Logger logger = LoggerFactory.getLogger(GeneralCodeEnumConverter.class);

    private final Map<String, T> codeEnumMap = MapUtil.newHashMap();
    private Class<T> enumType;

    public GeneralCodeEnumConverter(Class<T> enumType) {
        this.enumType = enumType;
        Arrays.stream(enumType.getEnumConstants())
            .forEach(elem -> {
                codeEnumMap.put(elem.getCode(), elem);
            });
    }

    @Override
    public T convert(String source) {
        T ret = codeEnumMap.get(source);

        if (ret == null) {
            logger.warn(StrUtil.format("枚举值不匹配，class:{}, 值：{}", enumType.getName(), source));
            throw BizExceptionFactory.badRequestException(
                "枚举值不匹配",
                StrUtil.format("枚举值不匹配，class:{}, 值：{}", enumType.getName(), source)
            );
        }

        return ret;
    }
}
